package cjlu.ea.h.Interceptor;

import cjlu.ea.h.common.R;
import cn.hutool.json.JSONUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
//        System.out.println("当前路径"+uri);
//        System.out.println("执行了TestInterceptor的preHandle方法");
        if(request.getHeader("token")!=null||uri.contains("/login")||uri.contains("/user/info")){
            //存在token表示已经登录，放行
            return true;
        }else{
            // 否则拦截返回未登录状态码
            returnJson(response,50010);
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("执行了TestInterceptor的postHandle方法");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("执行了TestInterceptor的afterHandle方法");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    private void returnJson(HttpServletResponse response, Integer code) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            String res = JSONUtil.toJsonStr(R.error(code));
            writer.print(res);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

}
